
#include"process_lock.h"

void fork_call()
{
	int p1, p2;
	while ((p1 = fork()) == -1) 
	{
		;
	}
	if (p1 == 0)
	{
		for (int i = 0; i < 1000; i++)
		{
			printf("daughter%d\n", i);
		}
	}
	else
	{
		while ((p2 = fork()) == -1)
		{
			;
		}
		if (p2 == 0)
		{
			for (int i = 0; i < 1000; i++)
			{
				printf("son%d\n", i);
			}
		}
		else
		{
			for (int i = 0; i < 1000; i++)
			{
				printf("parent%d\n", i);
			}
		}
	}
}

void fork_lock()
{
	int p1, p2, i;
	while ((p1 = fork()) == -1)
	{
		;
	}
	if (p1 == 0)
	{
		lockf(1, 1, 0);
		for (int i = 0; i < 10; i++)
		{
			printf("daughter%d\n", i);
		}
		lockf(1, 0, 0);
	}
	else
	{
		while ((p2 = fork()) == -1)
			;
		if (p2 == 0)
		{
			lockf(1, 1, 0);
			for (int i = 0; i < 10; i++)
			{
				printf("son%d\n", i);
			}
			lockf(1, 0, 0);
		}
		else
		{
			lockf(1, 1, 0);
			for (int i = 0; i < 10; i++)
			{
				printf("parent%d\n", i);
			}
			lockf(1, 0, 0);
		}
	}
}


void file_lock()
{
	int p1,p2,i;
	int *f = fopen("lockf.txt","w+");
	if(f == NULL)
	{
		printf("Fail to create file");
		exit(-1);
	}
	while((p1 = fork()) == -1)
	{
		;
	}
	if(p1 == 0)
	{
		lockf(*f, 1, 0);
		for(i = 0; i < 10; i++)
		{
			fprintf(f, "daughter%d\n", i);
		}		
		lockf(*f, 0, 0);
	}
	else
	{
		while((p2 = fork()) == -1)
		{
			;
		}
		if(p2 == 0)
		{
			lockf(*f, 1, 0);
			for(i = 0; i < 10; i++)
			{
				fprintf(f, "son%d\n", i);
			}
			lockf(*f, 0, 0);
		}
		else
		{
			wait(NULL);
			lockf(*f, 1, 0);
			for(i = 0; i < 10; i++)
			{
				fprintf(f, "parent%d\n", i);
			}
			lockf(*f, 0, 0);
		}
	}
	fclose(f);
}
